package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

/**
  获取请求参数
*/
func main() {
	engine := gin.Default()
	engine.GET("/search", func(context *gin.Context) {
		query := context.DefaultQuery("name", "默认值")
		age := context.Query("age")
		fmt.Printf("参数name:  %v  参数age： %v ", query, age)
		//接收到请求后再响应结果
		context.JSON(http.StatusOK, gin.H{"status": "OK", "msg": "message..."})
	})

	engine.POST("/search", func(context *gin.Context) {
		name := context.DefaultPostForm("name", "默认值")
		age := context.PostForm("age")
		fmt.Printf("参数name:  %v  参数age： %v ", name, age)
		//接收到请求后再响应结果
		context.JSON(http.StatusOK, gin.H{"status": "OK", "msg": "message..."})
	})

	engine.POST("/formJson", func(c *gin.Context) {
		//读取row格式请求体数据
		b, _ := c.GetRawData()
		// 定义map或结构体
		var m map[string]interface{}
		// 反序列化
		_ = json.Unmarshal(b, &m)
		fmt.Println("JSON请求参数", m)
		c.JSON(http.StatusOK, m)
	})

	//获取路径参数
	engine.GET("/search/:name/:age", func(context *gin.Context) {
		name := context.Param("name")
		age := context.Param("age")
		context.JSON(http.StatusOK, gin.H{"name": name, "age": age, "msg": "路径参数测试"})
	})

	engine.Run(":8088")
}
